<template>
	<view>
		
		<view style="width: 100%;padding: 12px 6px 12px 6px;">
			<a-button style="width: 88px;margin: 6px;" type="primary" @click="exportFn">导出</a-button>
			<a-button style="width: 88px;margin: 6px" type="primary" @click="handleAdd">新增</a-button>
			<a-button style="width: 88px;margin: 6px" type="primary" @click="getAllMecList">刷新</a-button>
		</view>
		
		<!-- 		<unicloud-db ref="udb" :collection="collectionList" :gettree="true"
			field="name,parent_id,mobile,note,start_time,end_time,status,update,create_time,area,address" :where="where"
			page-data="replace" :orderby="orderby" :getcount="true" :page-size="pagination.pageSize"
			:page-current="pagination.current" v-slot:default="{data,loading,error,options}" :options="options"
			loadtime="manual" @load="onqueryload"> -->
		<ag-grid-vue style="width: 100%; height: 90vh;" class="ag-theme-alpine" @grid-ready="onGridReady"
			@rowDoubleClicked="rowDoubleClick" :columnDefs="columnDefs" @rowClick="onRowClick" :getRowId="getRowId"
			:paginationAutoPageSize="true" :defaultColDef="defaultColDef" :rowData="dataSources">
		</ag-grid-vue>

		<view class="cu-popup" v-if="editStatue">
			<view class="cu-popup-content">
				<mec-edit @onClose="()=>editStatue=false" :id="currentRowId"></mec-edit>
			</view>
		</view>
		<!-- </unicloud-db> -->


		<!-- <uni-popup ref="list_subjectpage" :mask-click="false">
			<list-subjectpage :mechanismId="cur_mechanism_id" @closepop="()=>$refs.list_subjectpage.close()">
			</list-subjectpage>
		</uni-popup>

		<uni-popup ref="list_mechanism" :mask-click="false">
			<list-mechanism :mechanismId="cur_mechanism_id" @closepop="()=>$refs.list_mechanism.close()">
			</list-mechanism>
		</uni-popup> -->
		<!-- 
		<view class="uni-header">
			<view class="uni-group">
				<view class="uni-title"></view>
				<view class="uni-sub-title"></view>
			</view>
			<view class="uni-button-group">
				<view>
					<button @click="uploadExcel">test导入</button>
				</view>
			</view>
		</view> -->

		<!-- 	<view class="uni-container">
			<unicloud-db ref="udb" :collection="collectionList" :gettree="true"
				field="name,parent_id,mobile,note,start_time,end_time,status,update,create_time,area,address"
				:where="where" page-data="replace" :orderby="orderby" :getcount="true" :page-size="pagination.pageSize"
				:page-current="pagination.current" v-slot:default="{data,loading,error,options}" :options="options"
				loadtime="manual" @load="onqueryload">

				<uni-fab v-show="addStatus" @fabClick="handleAdd" :popMenu="false" :horizontal="'left'"
					:vertical="'bottom'">添加</uni-fab>
				<a-table :indentSize="30" bordered :rowKey="(record,index)=>record._id" :pagination="pagination"
					:dataSource="dataSources" :columns="columns">

					<template v-for="x1 in ['name']" :slot="x1" slot-scope="text, record, index">

						<uni-easyinput v-if="record._id === editingKey" style="margin: -5px 0" type="text"
							v-model="findObject(record._id)[x1]">
						</uni-easyinput>
						<template v-else>
							{{text}}
							<a-tag color="blue">{{record.children.length}}</a-tag>
						</template>

					</template>

					<template v-for="a1 in [ 'area']" :slot="a1" slot-scope="text, record, index">
						<div>
							<template v-if="record._id === editingKey">
								<el-cascader size="large" :options="cityreg" v-model="findObject(record._id)[a1]"
									@change="handleChange">
								</el-cascader>

							</template>

							<template v-else>
								{{getAreaText(record._id)}}
							</template>

						</div>
					</template>

					<template v-for="c1 in [ 'note', 'mobile','address']" :slot="c1" slot-scope="text, record, index">
						<div>

							<uni-easyinput v-if="record._id === editingKey" style="margin: -5px 0" type="text"
								v-model="findObject(record._id)[c1]">
							</uni-easyinput>

							<template v-else>
								{{
									text
								}}
							</template>

						</div>
					</template>


					<template v-for="c2 in ['start_time','end_time','create_time']" :slot="c2"
						slot-scope="text,record,index">
						<div>
							<template v-if="record._id === editingKey && ['start_time','end_time'].includes(c2)">
								<uni-datetime-picker returnType="timestamp" type="datetime"
									v-model="findObject(record._id)[c2]" />
							</template>
							<template v-else>
								<uni-dateformat :threshold="[0, 0]" :date="text"></uni-dateformat>
							</template>
						</div>
					</template>


					<template v-for="c3 in ['status']" :slot="c3" slot-scope="text,record,index">
						<div>

							<template v-if="record._id === editingKey">
								<uni-data-checkbox @change="setStatusValue($event,record._id)"
									:value="findObject(record._id).status" :localdata="formOptions.status_localdata">
								</uni-data-checkbox>
							</template>
							<template v-else>
								<a-tag :color="text==0?'red':'blue'">
									{{options.status_valuetotext[text]}}
								</a-tag>
							</template>

						</div>
					</template>

					<template slot="operation" slot-scope="text, record, index">
						<div class="editable-row-operations">
							<span v-if="editingKey === record._id">
								<a @click=" save(record._id)">保存</a>
								<a-popconfirm title="确认关闭?" @confirm=" cancel(index)">
									<a>关闭</a>
								</a-popconfirm>
							</span>
							<span v-else>
								<a :disabled="editingKey !== ''" @click=" edit(record._id)">编辑</a>
								<a :disabled="editingKey !== ''" @click="del(record._id)">删除</a>
								<a :disabled="editingKey !== ''" @click="handleAdd(record._id)">增加下级</a>
								<a @click="showJiAdmin(record._id)">查看管理</a>
								<a @click="showMechanism(record._id)">题库</a>
							</span>
						</div>
					</template>



				</a-table>


			</unicloud-db>
		</view> -->
	</view>
</template>

<script>
	// import "@/pages/mechanism/component/local-en.js";
	// import "@/pages/mechanism/component/local-en.js";

	import {
		regionDataPlus,
		CodeToText,
		TextToCode
	} from 'element-china-area-data'
	import * as XLSX from '@/js_sdk/xlsx/dist/xlsx.full.min.js'
	import cudateform from '@/pages/mechanism/component/cudateform.vue'
	import mecstatus from '@/pages/mechanism/component/mecstatus.vue'
	import mecstatusEditor from '@/pages/mechanism/component/mecstatusEditor.vue'
	import cucity from '@/pages/mechanism/component/cucity.vue'
	import mecstatusSearch from '@/pages/mechanism/component/mecstatusSearch.vue'
	import mecstatusSearchFloting from '@/pages/mechanism/component/mecstatusSearchFloting.vue'
	import cityFilter from '@/pages/mechanism/component/cityFilter.vue'
	import cityFilterFloting from '@/pages/mechanism/component/cityFilterFloting.vue'
	import opear from '@/pages/mechanism/component/opear.vue'
	import edit from '@/pages/mechanism/edit.vue'
	import {
		agConfig
	} from '@/pages/mechanism/table.config.js'
	import Vue from 'vue'

	import {
		enumConverter,
		filterToWhere
	} from '@/js_sdk/validator/mechanism.js';

	import {
		AgGridVue
	} from "ag-grid-vue";
	import 'ag-grid-enterprise';
	import {
		LicenseManager
	} from "ag-grid-enterprise";
	LicenseManager.prototype.validateLicense = function() {
		return true;
	};
	const db = uniCloud.database()
	// 表查询配置
	const dbOrderBy = '' // 排序字段
	const dbSearchFields = [] // 模糊搜索字段，支持模糊搜索的字段列表。联表查询格式: 主表字段名.副表字段名，例如用户表关联角色表 role.role_name
	// 分页配置
	const pageSize = 500
	const pageCurrent = 1
	const orderByMapping = {
		"ascending": "asc",
		"descending": "desc"
	}

	export default {
		components: {
			AgGridVue,
			cudateform,
			mecstatus,
			mecstatusEditor,
			cucity,
			mecstatusSearch,
			mecstatusSearchFloting,
			cityFilter,
			cityFilterFloting,
			opear,
			'mec-edit': edit
		},
		data() {
			return {
				editStatue: false,
				getRowId: null,
				gridApi: null,
				gridColumnApi: null,
				columnDefs: agConfig,
				rowData: null,
				selectedOptions: [],
				cityreg: regionDataPlus,
				cur_mechanism_id: '',
				dataMapPosition: {},
				addStatus: true,
				pagination: {
					current: 1,
					total: 0,
					pageSize: 500, //每页中显示10条数据
					showSizeChanger: true,
					pageSizeOptions: ["10", "20", "50", "300"], //每页中显示的数据，
					showTotal: total => `共有 ${total} 条数据` //分页中显示总的数据
				},

				editingKey: '',
				dataSources: [],
				editableData: {},
				defaultColDef: {
					// editable: true,
					width: 150,
					resizable: true,
					filter: true,
					floatingFilter: true
				},
				columns: [{
						title: '机构昵称',
						dataIndex: 'name',
						resizable: true,
						scopedSlots: {
							customRender: 'name'
						},
					},
					{
						title: '联系手机',
						dataIndex: 'mobile',
						resizable: true,
						scopedSlots: {
							customRender: 'mobile'
						},
					},
					{
						title: '负责人',
						dataIndex: 'note',
						resizable: true,
						scopedSlots: {
							customRender: 'note'
						},
					},
					{
						title: '授权开始日期',
						dataIndex: 'start_time',
						resizable: true,
						scopedSlots: {
							customRender: 'start_time'
						},
					},
					{
						title: '授权结束日期',
						dataIndex: 'end_time',
						resizable: true,
						scopedSlots: {
							customRender: 'end_time'
						},
					},
					{
						title: '机构状态',
						dataIndex: 'status',
						resizable: true,
						scopedSlots: {
							customRender: 'status'
						},
					},
					{
						title: '地址',
						dataIndex: 'address',
						resizable: true,
						scopedSlots: {
							customRender: 'address'
						}
					},
					{
						title: '区域',
						dataIndex: 'area',
						resizable: true,
						scopedSlots: {
							customRender: 'area'
						}
					},
					{
						title: '创建日期',
						dataIndex: 'create_time',
						resizable: true,
						scopedSlots: {
							customRender: 'create_time'
						},
					},
					{
						resizable: true,
						title: '操作',
						dataIndex: 'operation',
						scopedSlots: {
							customRender: 'operation'
						},
					}
				],
				collectionList: "mechanism",
				query: '',
				where: '',
				orderby: dbOrderBy,
				orderByFieldName: "",
				selectedIndexs: [],
				formOptions: {
					"status_localdata": [{
							"value": 0,
							"text": "欠费"
						},
						{
							"value": 1,
							"text": "正常"
						},
						{
							"value": 2,
							"text": "终止"
						}
					]
				},
				options: {
					pageSize,
					pageCurrent,
					filterData: {
						"status_localdata": [{
								"value": 0,
								"text": "禁用"
							},
							{
								"value": 1,
								"text": "正常"
							},
							{
								"value": 2,
								"text": "终止"
							}
						]
					},
					...enumConverter
				},
				imageStyles: {
					width: 64,
					height: 64
				},
				exportExcel: {
					"filename": "mechanism.xls",
					"type": "xls",
					"fields": {
						"机构昵称": "name",
						"上级": "parent_id",
						"联系手机": "mobile",
						"负责人": "note",
						"区域": "area",
						"地址": "address",
						"授权开始日期": "start_time",
						"授权结束日期": "end_time",
						"机构状态": "status",
						"更新日期": "update"
					}
				},
				exportExcelData: [],
				rowId: 1,
				currentRowId: '',
				importExcel: {
					"fields": {
						"机构名称": "name",
						"机构管理账号": "username",
						"负责人": "note",
						"区域": "area",
						"手机": "mobile",
						"电话": "tel",
						"地址": "address",
						"管辖地区": "area",
						"备注": "common",
						"机构建立日期": "create_time",
						"授权结束日期": "end_time",
					}
				},
				parser: {
					yyyy: (dateObj) => {
						return this.pad(dateObj.year, 4)
					},
					yy: (dateObj) => {
						return this.pad(dateObj.year)
					},
					MM: (dateObj) => {
						return this.pad(dateObj.month)
					},
					M: (dateObj) => {
						return this.dateObj.month
					},
					dd: (dateObj) => {
						return this.pad(dateObj.day)
					},
					d: (dateObj) => {
						return this.dateObj.day
					},
					hh: (dateObj) => {
						return this.pad(dateObj.hour)
					},
					h: (dateObj) => {
						return this.dateObj.hour
					},
					mm: (dateObj) => {
						return this.pad(dateObj.minute)
					},
					m: (dateObj) => {
						return dateObj.minute
					},
					ss: (dateObj) => {
						return this.pad(dateObj.second)
					},
					s: (dateObj) => {
						return dateObj.second
					},
					SSS: (dateObj) => {
						return this.pad(dateObj.millisecond, 3)
					},
					S: (dateObj) => {
						return dateObj.millisecond
					},
				}
			}
		},
		onLoad() {
			this._filter = {}
			this.dataMapPosition = new Map()
			// const data = [];
			// for (let i = 0; i < 100; i++) {
			// 	data.push({
			// 		key: this.$uuid(),
			// 		name: '机构昵称',
			// 		mobile: '联系手机',
			// 		note: '负责人',
			// 		start_time: 1602662469398,
			// 		end_time: 1602662469398,
			// 		status: 0,
			// 		create_time: 1602662469398
			// 	});
			// }


		},
		created() {
			this.getRowId = (p) => {
				return p.data.indexId
			}
		},
		beforeMount() {

		},
		mounted() {
			//	console.log('cachedata',this.cacheData)
		},
		onReady() {
			// this.$refs.udb.loadData()
			this.getAllMecList()
			uni.$on('refreshData',()=>{
				console.log('刷新表格')
				this.getAllMecList()
			})

		},
		onShow() { 
		//	this.getAllMecList()
		},
		methods: {
			exportFn(){
				this.gridApi.exportDataAsExcel()
			},
			pad(str, length = 2) {
				str += ''
				while (str.length < length) {
					str = '0' + str
				}
				return str.slice(-length)
			},
			getDate(time) {
				if (time instanceof Date) {
					return time
				}
				switch (typeof time) {
					case 'string': {
						// 2020-12-12T12:12:12.000Z、2020-12-12T12:12:12.000
						if (time.indexOf('T') > -1) {
							return new Date(time)
						}
						return new Date(time.replace(/-/g, '/'))
					}
					default:
						return new Date(time)
				}
			},
			formatDate(date, format = 'yyyy/MM/dd hh:mm:ss') {
				const self = this 
				if (!date && date !== 0) {
					return ''
				}
				date = this.getDate(date)
				const dateObj = {
					year: date.getFullYear(),
					month: date.getMonth() + 1,
					day: date.getDate(),
					hour: date.getHours(),
					minute: date.getMinutes(),
					second: date.getSeconds(),
					millisecond: date.getMilliseconds()
				}
				const tokenRegExp = /yyyy|yy|MM|M|dd|d|hh|h|mm|m|ss|s|SSS|SS|S/
				let flag = true
				let result = format
				while (flag) {
					flag = false
					result = result.replace(tokenRegExp, function(matched) {
						flag = true
						return self.parser[matched](dateObj)
					})
				}
				return result
			},
			friendlyDate(time, {
				locale = 'zh',
				threshold = [60000, 3600000],
				format = 'yyyy/MM/dd hh:mm:ss'
			}) {
				if (time === '-') {
					return time
				}
				if (!time && time !== 0) {
					return ''
				}
				const localeText = {
					zh: {
						year: '年',
						month: '月',
						day: '天',
						hour: '小时',
						minute: '分钟',
						second: '秒',
						ago: '前',
						later: '后',
						justNow: '刚刚',
						soon: '马上',
						template: '{num}{unit}{suffix}'
					},
					en: {
						year: 'year',
						month: 'month',
						day: 'day',
						hour: 'hour',
						minute: 'minute',
						second: 'second',
						ago: 'ago',
						later: 'later',
						justNow: 'just now',
						soon: 'soon',
						template: '{num} {unit} {suffix}'
					}
				}
				const text = localeText[locale] || localeText.zh
				let date = this.getDate(time)
				let ms = date.getTime() - Date.now()
				let absMs = Math.abs(ms)
				if (absMs < threshold[0]) {
					return ms < 0 ? text.justNow : text.soon
				}
				if (absMs >= threshold[1]) {
					return this.formatDate(date, format)
				}
				let num
				let unit
				let suffix = text.later
				if (ms < 0) {
					suffix = text.ago
					ms = -ms
				}
				const seconds = Math.floor((ms) / 1000)
				const minutes = Math.floor(seconds / 60)
				const hours = Math.floor(minutes / 60)
				const days = Math.floor(hours / 24)
				const months = Math.floor(days / 30)
				const years = Math.floor(months / 12)
				switch (true) {
					case years > 0:
						num = years
						unit = text.year
						break
					case months > 0:
						num = months
						unit = text.month
						break
					case days > 0:
						num = days
						unit = text.day
						break
					case hours > 0:
						num = hours
						unit = text.hour
						break
					case minutes > 0:
						num = minutes
						unit = text.minute
						break
					default:
						num = seconds
						unit = text.second
						break
				}

				if (locale === 'en') {
					if (num === 1) {
						num = 'a'
					} else {
						unit += 's'
					}
				}

				return text.template.replace(/{\s*num\s*}/g, num + '').replace(/{\s*unit\s*}/g, unit).replace(
					/{\s*suffix\s*}/g,
					suffix)
			},
			rowDoubleClick(e) {
				console.log(e)
				this.currentRowId = e.data._id
				this.editStatue = true
			},
			onGridReady(params) {
				this.gridApi = params.api;
				this.gridColumnApi = params.columnApi;
			},
			async getAllMecList() {
				uni.showLoading()
				const responseTotal = await db.collection('mechanism').count()
				const size = responseTotal.result.total
				// const size = 10
				if (size > 0) {
					let total = size
					let processSize = 0
					let position = 1
					let allData = []
					while (processSize < total) {
						const responseData = await db.collection('mechanism').skip(processSize).limit(500).get()
						if (responseData.result.data.length > 0) {
							responseData.result.data.forEach((e) => {
								e.indexId = position++
								e.create_time = this.friendlyDate(e.create_time, {
									locale: 'zh',
									threshold: [0, 0],
									format: 'yyyy/MM/dd hh:mm:ss'
								})
								e.end_time = this.friendlyDate(e.end_time, {
									locale: 'zh',
									threshold: [0, 0],
									format: 'yyyy/MM/dd hh:mm:ss'
								})
								allData.push(e)
							})
						}
						processSize += responseData.result.data.length
					}
					this.dataSources = allData
				}
				uni.hideLoading()
			},
			uploadExcel() {
				const self = this
				uni.chooseFile({
					async success(res) {
						// const response = await db.collection('mechanism').add({
						// 	name:'测试222'
						// })
						// console.log(response)
						// if(response.result.code==0){

						// }

						// return 


						const url = res.tempFilePaths[0];
						const data = await (await fetch(url, {
							mode: 'no-cors'
						})).arrayBuffer();
						const userData = []
						/* data is an ArrayBuffer */
						const workbook = XLSX.read(data);
						const xlsxData = XLSX.utils.sheet_to_json(workbook.Sheets[workbook.SheetNames[0]])
						let keyMap = Object.keys(self.importExcel.fields)
						let importData = []
						for (let s of xlsxData) {
							let d = {}

							for (let t of keyMap) {
								d[self.importExcel.fields[t]] = s[t]
							}
							d.end_time = Number(new Date('2022', '11', '01', '00', '00', '00'))
							d.create_time = new Date(d.create_time + ' 00:00:00').getTime()
							d.status = 1
							d.tel = '' + d.tel
							d.mobile = '' + d.mobile
							if (d.area != '') {
								let area = d.area.split('/')
								let codeArea = []
								console.log(area)
								if (area.length == 2) {
									codeArea[TextToCode[area[0]].code,
										TextToCode[area[0]][area[1]].code]
									// console.log(
									// TextToCode[area[0]].code,
									// TextToCode[area[0]][area[1]].code
									// )
								}

								if (area.length == 3) {
									codeArea[TextToCode[area[0]].code,
										TextToCode[area[0]][area[1]].code,
										TextToCode[area[0]][area[1]][area[2]].code]
									// console.log(
									// TextToCode[area[0]].code,
									// TextToCode[area[0]][area[1]].code,
									// TextToCode[area[0]][area[1]][area[2]].code)
								}
								d.area = codeArea
							}
							const {
								status,
								create_time,
								end_time,
								name,
								address,
								note,
								area,
								tel,
								mobile,
								common
							} = d
							const formdata = {
								status,
								create_time,
								end_time,
								name,
								address,
								note,
								area,
								tel,
								mobile,
								common
							}
							console.log(formdata)
							let response = await db.collection('mechanism').add(formdata)

							if (response.result.code == 0 && d.username != undefined) {

								let usertemp = {
									dcloud_appid: ['__UNI__653656E'],
									password_source: "123456",
									password: "123456",
									username: d.username,
									status: 1,
									mobile: d.mobile,
									mechanism_id: response.result.id,
									role: ['jigou']
								}

								self.$request('registerUser', usertemp, {
									functionName: 'uni-id-cf'
								}).then(res => {
									console.log('新增成功', d.username)
									// uni.showToast({
									// 	title: '新增成功'
									// })
									// this.getOpenerEventChannel().emit('refreshData')
									// setTimeout(() => uni.navigateBack(), 500)
								}).catch(err => {
									uni.showModal({
										content: err.message || '请求服务失败',
										showCancel: false
									})
								}).finally(err => {
									uni.hideLoading()
								})

							}
						}




						// console.log(workbook.Sheets[workbook.SheetNames[0]])
						/* DO SOMETHING WITH workbook HERE */

					}
				})

			},

			getAreaText(id) {
				const target = this.findObject(id)
				let str = ''
				if (target.area) {
					target.area.forEach(e => {
						str += CodeToText[e]
					})
					return str
				}
				return ''
			},
			showMechanism(id) {
				this.cur_mechanism_id = id
				console.log(this.cur_mechanism_id)
				this.$refs.list_subjectpage.open()
			},
			showJiAdmin(id) {
				this.cur_mechanism_id = id
				this.$refs.list_mechanism.open()
			},
			setMechanism(id) {
				this.cur_mechanism_id = id
				this.$refs.add_mechanism.open()
			},
			setStatusValue(envent, id) {
				let model = this.findObject(id)
				model.status = model.status ? 0 : 1
			},
			findObject(key) {
				let data_position_array = this.getObjectPosition(key)
				let target = this.dataSources[parseInt(data_position_array[0])]
				for (let i = 1; i < data_position_array.length; i++) {
					let temp = target
					target = target.children[parseInt(data_position_array[i])]
				}
				return target
			},
			getObjectPosition(key) {
				let position = this.dataMapPosition.get(key)
				if (typeof position == 'number') {
					position = position.toString()
				}
				return position.split(',')
			},
			handleChange(value) {
				console.log(value)
			},
			edit(key) {
				let target = this.findObject(key)
				this.editingKey = key;
				target.editable = true
			},
			del(key) {
				const cur_obj = this.findObject(key)
				const idList = []

				idList.push(cur_obj._id)
				const fndeep = function(data) {

					for (let j = 0; j < data.length; j++) {
						idList.push(data[j]._id)
						if (data[j].children.length > 0) {
							fndeep(data[j].children)
						}

					}
				}

				if (cur_obj.children.length > 0) {
					fndeep(cur_obj.children)
				}

				console.log(idList)

				//console.log(this.dataSources[key]['_id'])
				this.$refs.udb.remove(idList)
			},
			save(key) {

				let target = this.findObject(key)

				let updateTarget = this.$cloneObject(target)

				delete updateTarget.editable
				delete updateTarget._id
				delete updateTarget.children

				this.$refs.udb.update(target['_id'], {
					...updateTarget
				}, {
					toastTitle: '修改成功', // toast提示语
					success: (res) => { // 更新成功后的回调
						const {
							code,
							message
						} = res
						target = null

						//Object.assign(target, updateTarget)
						this.$forceUpdate()
					},
					fail: (err) => { // 更新失败后的回调
						const {
							message
						} = err
					},
					complete: () => { // 完成后的回调
						this.editingKey = '';
					}
				})


			},
			cancel(key) {
				const newData = [...this.dataSources];
				const target = newData.find(item => key === item.key);
				this.editingKey = '';
				if (target) {
					Object.assign(target, this.cacheData.find(item => key === item.key));
					delete target.editable;
					this.dataSources = newData;
				}
			},

			handleAdd(parentId = '') {
				
				uni.navigateTo({
					url:'/pages/mechanism/add'
				})
				// this.addStatus = false
				// let uuid = this.$uuid()
				// uuid = uuid.replaceAll('-', '')
				// const self = this
				// let newData = {
				// 	name: '机构昵称',
				// 	mobile: '联系手机',
				// 	note: '负责人',
				// 	start_time: Date.now(),
				// 	end_time: Date.now() + 86400,
				// 	status: 0,
				// 	address: '',
				// 	area: [],
				// 	parent_id: parentId,
				// 	create_time: Date.now(),
				// 	key: uuid
				// };


				// this.$refs.udb.add(newData, {
				// 	toastTitle: "新增成功",
				// 	success: (res) => {
				// 		const {
				// 			code,
				// 			message,
				// 			id
				// 		} = res.result

				// 		// if (parentId) {

				// 		self.$refs.udb.refresh()

				// 		// } else {
				// 		// 	self.dataSources.push({
				// 		// 		...newData,
				// 		// 		id
				// 		// 	});
				// 		// }



				// 	},
				// 	fail: (err) => {
				// 		const {
				// 			meessage
				// 		} = err
				// 	},
				// 	complete: () => {
				// 		self.addStatus = true
				// 	}
				// })


			},
			onqueryload(data) {
				console.log(data.length)
				//console.log(this.dataSources)
				this.dataSources = []
				const self = this
				const fndeep = function(data, lastPosition) {

					for (let j = 0; j < data.length; j++) {
						self.dataMapPosition.set(data[j]._id, lastPosition + ',' + j)
						if (data[j].children.length > 0) {
							fndeep(data[j].children, lastPosition + ',' + j)
						}

					}
				}
				for (let i = 0; i < data.length; i++) {
					let s = data[i]
					this.dataSources.push(s)
					this.dataMapPosition.set(s._id, i)

					if (s.children.length > 0) {
						fndeep(s.children, i)
					}

				}

			},
			getWhere() {
				const query = this.query.trim()
				if (!query) {
					return ''
				}
				const queryRe = new RegExp(query, 'i')
				return dbSearchFields.map(name => queryRe + '.test(' + name + ')').join(' || ')
			},
			search() {
				const newWhere = this.getWhere()
				this.where = newWhere
				this.$nextTick(() => {
					this.loadData()
				})
			},
			loadData(clear = true) {
				this.$refs.udb.loadData({
					clear
				})
			},
			onPageChanged(e) {
				this.selectedIndexs.length = 0
				this.$refs.table.clearSelection()
				this.$refs.udb.loadData({
					current: e.current
				})
			},
			navigateTo(url, clear) {
				// clear 表示刷新列表时是否清除页码，true 表示刷新并回到列表第 1 页，默认为 true
				uni.navigateTo({
					url,
					events: {
						refreshData: () => {
							this.loadData(clear)
						}
					}
				})
			},
			// 多选处理
			selectedItems() {
				var dataList = this.$refs.udb.dataList
				return this.selectedIndexs.map(i => dataList[i]._id)
			},
			// 批量删除
			delTable() {
				this.$refs.udb.remove(this.selectedItems(), {
					success: (res) => {
						this.$refs.table.clearSelection()
					}
				})
			},
			// 多选
			selectionChange(e) {
				this.selectedIndexs = e.detail.index
			},
			confirmDelete(id) {
				this.$refs.udb.remove(id, {
					success: (res) => {
						this.$refs.table.clearSelection()
					}
				})
			},
			sortChange(e, name) {
				this.orderByFieldName = name;
				if (e.order) {
					this.orderby = name + ' ' + orderByMapping[e.order]
				} else {
					this.orderby = ''
				}
				this.$refs.table.clearSelection()
				this.$nextTick(() => {
					this.$refs.udb.loadData()
				})
			},
			filterChange(e, name) {
				this._filter[name] = {
					type: e.filterType,
					value: e.filter
				}
				let newWhere = filterToWhere(this._filter, db.command)
				if (Object.keys(newWhere).length) {
					this.where = newWhere
				} else {
					this.where = ''
				}
				this.$nextTick(() => {
					this.$refs.udb.loadData()
				})
			},
			onShowSizeChange(current, pageSize) {
				console.log(current, pageSize);
			},
		}
	}
</script>

<style lang="scss" scoped>
	.editable-row-operations a {
		margin-right: 8px;
	}

	@import url('./list.css');
</style>
